package com.limingru.online_class.utils;

import java.security.MessageDigest;

public class MD5Util {
    /**
     * MD5加密
     * @param str 需要加密的字符串
     * @return
     */
    public static String MD5Encode(String str) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] digest = md5.digest(str.getBytes());
            return bytes2Hex(digest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static char[] hexChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    /**
     * 将byte数组转化为16进制字符串
     * @param bytes {byte[]} 需要转换的字符串数组
     * @return
     */
    public static String bytes2Hex(byte[] bytes) {
        char[] chars = new char[bytes.length * 2];
        byte use;
        int index = 0;
        for (byte b: bytes) {
            if (b < 0) {
                use = (byte)(128 + b);
            } else {
                use = b;
            }
            chars[index++] = hexChar[use / 16];
            chars[index++] = hexChar[use % 16];
        }
        return new String(chars);
    }
}
